package com.alfy.sbdemo.websocketdemo.demo1;

import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * WebSocket 服务端，端点路径 /weksocket
 */
@Component
//@ServerEndpoint(value = "/websocket/{username}/{userId}", configurator = AuthConfigurator.class)
@ServerEndpoint(value = "/websocket/{username}/{userId}")
public class WebSocketEndpoint {

    /**
     * 客户端计数器
     */
    private static final AtomicInteger counter = new AtomicInteger(0);

    /**
     * 客户端 websocket 连接集合
     */
    private static final Set<WebSocketEndpoint> connections = new CopyOnWriteArraySet<>();

    /**
     * websocket 会话对象
     */
    private Session session = null;

    /**
     * 客户端编号
     */
    private Integer number = 0;

    /**
     * 构造器
     */
    public WebSocketEndpoint() {
        number = counter.incrementAndGet() - 1;
    }

    /**
     * open 事件：连接建立成功后触发
     *
     * @param session  正在通讯的客户端会话对象
     * @param username 端点路径参数·1
     * @param userId   端点路径参数·2
     */
    @OnOpen
    public void open(Session session, @PathParam("username") String username, @PathParam("userId") String userId) {
        System.out.println(username + "客户端进入会话房间, userId: " + userId + ", number: " + number + ", 参数：" + session.getQueryString());
        connections.add(this); // 记载客户端对象
        this.session = session; // 记载当前会话对象
        try {
            session.getBasicRemote().sendText("欢迎" + username + "进入房间, 当前序号: " + number + ", session: " + session.getId());
        } catch (IOException e) {
            System.out.println("ex: " + e.getMessage());
        }
    }

    /**
     * message 事件：接收传输的消息
     *
     * @param session  正在通讯的客户端会话对象
     * @param message  消息数据
     * @param username 端点路径参数·1
     */
    @OnMessage
    public void message(Session session, String message, @PathParam("username") String username) {
        if (session.isOpen()) {
            System.out.println(username + "（" + session.getId() + "）: " + message + ", 参数：" + session.getQueryString());
            for (WebSocketEndpoint client : connections) {
                synchronized (client) {
                    try {
                        // 移除自己
                        if (client.session.getId().equals(session.getId())) {
                            continue;
                        }
                        // 发送给其他客户端
                        client.session.getBasicRemote().sendText(message);
                    } catch (IOException e) {
                        System.out.println("ex: " + e.getMessage());
                    }
                }
            }
        }else {
            System.out.println("（message）会话已关闭 ~~~");
        }
    }

    /**
     * close 事件：连接断开时触发
     *
     * @param session  正在通讯的客户端会话对象
     * @param username 端点路径参数·1
     */
    @OnClose
    public void close(Session session, @PathParam("username") String username) {
        try {
            System.out.println(username + "客户端退出会话, session: " + session.getId());
            this.session.close();
        } catch (IOException e) {
            System.out.println("ex: " + e.getMessage());
        } finally {
            connections.remove(this);
        }
        // 测试出现异常问题
        if (username.equals("ex")) {
            throw new RuntimeException("测试异常");
        }
    }

    /**
     * error事件：连接异常时触发
     *
     * @param session   正在通讯的客户端会话对象
     * @param throwable 异常对象
     * @param username  端点路径参数·1
     */
    @OnError
    public void error(Session session, Throwable throwable, @PathParam("username") String username) {
        System.out.println(username + "客户端异常（" + session.getId() + "）, number: " + number + "throwable: " + throwable.getMessage());
    }

    /**
     * 获取所有客户端集合
     *
     * @return
     */
    public static Set<WebSocketEndpoint> getConnections() {
        return connections;
    }

    /**
     * 获取当前正在通讯的客户端会话对象
     *
     * @return
     */
    public Session getSession() {
        return session;
    }

}

//zhangsan客户端进入会话房间, userId: 1001, number: 1, 参数：name=%E8%B7%AF%E5%BE%84%E5%8F%82%E6%95%B01&age=15
//zhangsan（0）: 大家好，我是张三, 参数：name=%E8%B7%AF%E5%BE%84%E5%8F%82%E6%95%B01&age=15
//zhangsan客户端退出会话, session: 0